import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from form_component import FormComponent

class TableComponent:
    def __init__(self, parent, columns, defaults=None, create_form=None):
        self.parent = parent
        self.columns = columns if not defaults else list(defaults.keys())
        self.column_config = {col: col for col in self.columns}  # 存储列配置
        self.defaults = defaults or {}
        self._create_form = create_form if create_form else self._default_create_form
        self.create_table()
        self.create_controls()

    def create_table(self):
        self.tree = ttk.Treeview(self.parent, columns=self.columns, show='headings', selectmode='extended')
        for col in self.columns:
            self.tree.heading(col, text=self.column_config.get(col, col))
        self.tree.pack(fill='both', expand=True)
        
    def column(self, column_id, display_name):
        """设置列显示名称"""
        self.column_config[column_id] = display_name
        if hasattr(self, 'tree'):
            self.tree.heading(column_id, text=display_name)
        style = ttk.Style()
        style.configure('Treeview', background='#ffffff', foreground='#333333', font=('Arial', 11), rowheight=30)
        style.map('Treeview', background=[('selected', '#0078d7')], foreground=[('selected', '#ffffff')])
        
        # 绑定双击事件
        self.tree.bind('<Double-1>', self.on_double_click)
        # 绑定右键菜单事件
        self.tree.bind('<Button-3>', self.show_context_menu)

    def create_controls(self):
        control_frame = ttk.Frame(self.parent)
        control_frame.pack(fill='x', pady=5)

        ttk.Button(control_frame, text='添加', command=self.show_add_dialog).pack(side='left', padx=5)
        ttk.Button(control_frame, text='编辑', command=self.edit_selected).pack(side='left', padx=5)
        ttk.Button(control_frame, text='删除', command=self.delete_selected).pack(side='left', padx=5)
        ttk.Button(control_frame, text='一键开启', command=self.delete_selected).pack(side='right', padx=5)

    def add_row(self, values=None, refresh=False):
        if values is None and self.defaults:
            values = list(self.defaults.values())
        if refresh:
            self.clear()
            self.tree.insert('', 'end', values=values)
        else:
            self.tree.insert('', 'end', values=values)

    def clear(self):
        for i in self.tree.get_children():
            self.tree.delete(i)

    def dialog_form(self, mode='add', selected=None):
        dialog = tk.Toplevel(self.parent)
        dialog.title('添加新记录' if mode == 'add' else '编辑记录')
        
        # 计算窗口居中位置
        dialog.update_idletasks()
        width = dialog.winfo_width()
        height = dialog.winfo_height()
        x = (dialog.winfo_screenwidth() // 2) - (width // 2)
        y = (dialog.winfo_screenheight() // 2) - (height // 2)
        dialog.geometry(f'+{x}+{y}')
        
        defaults = {}
        if mode == 'edit' and selected:
            values = self.tree.item(selected, 'values')
            defaults = dict(zip(self.columns, values))
        elif mode == 'add' and self.defaults:
            defaults = self.defaults
            
        form = self._create_form(dialog, defaults, selected,mode)
    
        
        
    def _default_create_form(self, dialog, defaults, selected=None ,mode='add'):
        form = FormComponent(dialog, defaults)
        for col, display_name in self.column_config.items():
            form.text(col, display_name)
        form.create_form()
        return form
        
        def on_submit():
            data = form.get_data()
            if all(data.values()):
                if mode == 'add':
                    self.add_row(list(data.values()))
                else:
                    
                    self.tree.item(selected, values=list(data.values()))
                dialog.destroy()
            else:
                messagebox.showwarning('警告', '请填写所有字段')
                
        form.submit(on_submit)
        
    def show_add_dialog(self):
        self.dialog_form('add')
        
    def edit_selected(self):
        selected = self.tree.selection()
        if selected:
            self.dialog_form('edit', selected[0])
            
    def save_new_record(self, dialog, entries):
        values = [entry.get() for entry in entries]
        if all(values):
            self.add_row(values)
            dialog.destroy()
        else:
            messagebox.showwarning('警告', '请填写所有字段')
            
    def save_edited_record(self, dialog, item, entries):
        values = [entry.get() for entry in entries]
        if all(values):
            self.tree.item(item, values=values)
            dialog.destroy()
        else:
            messagebox.showwarning('警告', '请填写所有字段')

    def on_double_click(self, event):
        item = self.tree.identify('item', event.x, event.y)
        if item:
            self.dialog_form('edit', item)
            
    def delete_selected(self):
        selected = self.tree.selection()
        if selected:
            confirm = messagebox.askyesno('确认', '确定要删除选中的记录吗？')
            if confirm:
                self.tree.delete(selected)
                
    def show_context_menu(self, event):
        item = self.tree.identify('item', event.x, event.y)
        if item:
            menu = tk.Menu(self.parent, tearoff=0)
            menu.add_command(label='编辑', command=lambda: self.dialog_form('edit', item))
            menu.add_command(label='删除', command=lambda: self.delete_selected())
            menu.post(event.x_root, event.y_root)

if __name__ == '__main__':
    root = tk.Tk()
    
    # # 示例1: 使用列表初始化列名
    # table1 = TableComponent(root, ['ID', 'Name', 'Age'])
    # table1.add_row(['1', 'John', '25'])
    # table1.add_row(['2', 'Jane', '30'])
    
    # 示例2: 使用defaults参数初始化
    defaults = {
        'Email': 'zhangsan@example.com',
        'Name': '张三',
        'Password': '123456',
        'Dir': 'C:/Users/DELL/Videos/虾客/随机ab',
        # 'Avatar': 'C:/Users/DELL/Videos/虾客/随机ab/20250428183433-c_p.mp4',
        # 'Type': 'option1',
        # 'Agree': {'option1': True, 'option2': False}
    }
    # table2 = TableComponent(root, list(defaults.keys()))
    # table2.column("Name", "姓名")
    # table2.column("Email", "邮箱")
    # table2.column("Dir", "目录")
    # table2.add_row(list(defaults.values()))
    
    # 示例3: 使用create_form参数自定义表单
    def custom_form(dialog, defaults, selected=None,mode='add'):
        form = FormComponent(dialog, defaults)
        form.text('Name', '姓名')
        form.text('Email', '邮箱')
        form.text('Password', '密码')
        form.file('Dir', '目录')
        form.create_form()
        def on_submit():
            data = form.get_data()
            if all(data.values()):
                if mode == 'add':
                    table3.add_row(list(data.values()))
                else:
                    table3.tree.item(selected, values=list(data.values()))
                dialog.destroy()
            else:
                messagebox.showwarning('警告', '请填写所有字段')
                
        form.submit(on_submit)
        return form
        
    table3 = TableComponent(root, list(defaults.keys()), create_form=custom_form)
    table3.column('Name', '用户名')
    table3.column('Email', '电子邮箱')
    table3.column('Password', '密码')
    table3.add_row(list(defaults.values()))
    root.mainloop()